package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "移动端用户相关")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private CategoryService categoryService;

    @PostMapping("/user/login")
    public Result login(@RequestBody UserLoginDTO dto) {
        User user = userService.login(dto);
        UserLoginVO loginVO = new UserLoginVO();
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        claims.put("openId", user.getOpenid());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        loginVO = UserLoginVO.builder().id(user.getId())
                .openid(user.getOpenid())
                .token(token).build();
        return Result.success(loginVO);
    }
    @GetMapping("/category/list")
    public Result getTypeListByStatus(Integer type){
         List<Category> category = categoryService.getTypeListByStatus(type);
        return Result.success(category);
    }
    @Cacheable(cacheNames = "categoryCache",key = "#categoryId")
    @GetMapping("/setmeal/list")
    public Result getsetmealByCategoryId(@RequestParam Long categoryId){
      List<SetmealVO>  categorys = categoryService.getsetmealByCategoryId(categoryId);
        return Result.success(categorys);
    }
    @Cacheable(cacheNames = "dishCache",key = "#categoryId")
    @GetMapping("/dish/list")
    public Result getDishByCategoryId(@RequestParam Long categoryId){
        List<DishVO>  dishes = categoryService.getDishByCategoryId(categoryId);
        return Result.success(dishes);
    }
    @Cacheable(cacheNames = "dishCache",key = "#id")
    @GetMapping("/setmeal/dish/{id}")
    public Result getDishesBySetmealId(@PathVariable Long id){
       List<DishVO> dishes = categoryService.getDishesBySetmealId(id);
        return Result.success(dishes);
    }
}
